<template>
  <div class="map">
    <div class="container">
      <!-- 确认路径规划 -->
      <el-button class="submit-path-plan" type="success" plain @click="submitPathPlan">确认规划</el-button>
      <!-- 设置规划策略 -->
      <el-popover
        class="setting"
        placement="bottom"
        width="400"
        trigger="click"
      >
        <el-radio-group v-model="policy">
          <el-radio :label="10">默认策略</el-radio>
          <el-radio :label="12">躲避拥堵</el-radio>
          <el-radio :label="13">不走高速</el-radio>
          <el-radio :label="14">避免收费</el-radio>
          <el-radio :label="19">高速优先</el-radio>
          <el-radio :label="15">躲避拥堵&不走高速</el-radio>
          <el-radio :label="17">躲避拥堵&避免收费</el-radio>
          <el-radio :label="20">躲避拥堵&高速优先</el-radio>
          <el-radio :label="18">避免拥堵&避免收费&不走高速</el-radio>
        </el-radio-group>

        <el-button slot="reference" icon="el-icon-s-tools" />
      </el-popover>
      <!-- 路径规划面板 -->
      <div id="panel" />
      <!--
        amap-manager： 地图管理对象
        vid：地图容器节点的ID
        zooms： 地图显示的缩放级别范围，在PC上，默认范围[3,18]，取值范围[3-18]；在移动设备上，默认范围[3-19]，取值范围[3-19]
        center： 地图中心点坐标值
        plugin：地图使用的插件
        events： 事件
      -->
      <el-amap class="amap-box" :amap-manager="amapManager" :vid="'amap-vue'" :zoom="zoom" :plugin="plugin" :center="center" :events="events" />
    </div>
  </div>
</template>

<script>
import { AMapManager, lazyAMapApiLoaderInstance } from 'vue-amap'
// import AMap from 'AMap'
// import AMapUI from 'AMapUI'
const amapManager = new AMapManager()
export default {
  name: 'Elamapmarker',
  props: {
    data: {
      type: Object,
      require: true,
      default: () => {}
    }
  },
  data() {
    const self = this
    return {
      amapManager,
      center: [116.379028, 39.865042],
      zoom: 17,
      lng: 0,
      lat: 0,
      loaded: false,
      policy: 10,
      truckDriving: null,
      path: [], // 计算后的路径
      pathPlanResult: {
        isPathPlanSuccess: false, // 是否路径规划成功
        data: null // 规划结果
      },
      events: {
        init(e) {
          lazyAMapApiLoaderInstance.load().then(() => {
          })
        },
        // 鼠标点击事件
        click(e) {}
      },
      // 一些工具插件
      plugin: [
        {
          pName: 'Geocoder',
          events: {
            init(o) {}
          }
        },
        // 驾车路线规划
        {
          pName: 'Driving',
          events: {
            init(e) {}
          }
        },
        // 货车路径规划
        {
          pName: 'TruckDriving',
          events: {
            init(e) {
              if (self.data && self.data.orderAddress && self.data.storageLongitude && self.data.storageLatitude) {
                let start = { longitude: self.data.storageLongitude, latitude: self.data.storageLatitude }
                let line = self.data.orderAddress
                self.changePolicy(start, line)
              } else {
                self.$message.warning('暂无经纬度信息无法规划路线')
              }
            }
          }
        },
        // 定位
        {
          pName: 'Geolocation',
          events: {
            init(o) {
              if (self.selectedarea == '') {
                // o是高德地图定位插件实例
                o.getCurrentPosition((status, result) => {
                  if (result && result.position) {
                    // 设置经度
                    self.lng = result.position.lng
                    // 设置维度
                    self.lat = result.position.lat
                    // 设置坐标
                    self.center = [self.lng, self.lat]
                    // load
                    self.loaded = true
                    // 页面渲染好后
                    self.$nextTick()
                  }
                })
              }
            }
          }
        },
        // 工具栏
        {
          pName: 'ToolBar',
          events: {
            init(instance) {
            }
          }
        },
        // 鹰眼
        {
          pName: 'OverView',
          events: {
            init(instance) {
            }
          }
        }
      ]
    }
  },
  watch: {
    policy: function(val) {
      if (this.data && this.data.orderAddress && this.data.storageLongitude && this.data.storageLatitude) {
        let start = { longitude: this.data.storageLongitude, latitude: this.data.storageLatitude }
        let line = this.data.orderAddress
        this.changePolicy(start, line)
      } else {
        this.$message.warning('暂无经纬度信息无法规划路线')
      }
    }
  },
  mounted() {
  },
  methods: {
    // 切换路径规划规则
    changePolicy(start, line) {
      let self = this
      if (this.truckDriving) {
        this.truckDriving.clear()
      }
      this.path = this.computeDis(start, line)
      let size = null
      if (this.data && this.data.vehicle) {
        switch (this.data.vehicle.loadType) {
          case 'MINIATURE': // 微型货车
            size = 1
            break
          case 'LIGHT': // 轻型货车
            size = 2
            break
          case 'MIDSIZE': // 中型货车
            size = 3
            break
          case 'HEAVY': // 重型货车
            size = 4
            break
        }
      }
      this.truckDriving = new AMap.TruckDriving({
        map: amapManager._map,
        province: this.data.plateNumber.substr(0, 1),
        number: this.data.plateNumber.substr(1),
        extensions: 'all',
        size: size,
        width: this.data.vehicle ? this.data.vehicle.width : null,
        height: this.data.vehicle ? this.data.vehicle.height : null,
        // weight: this.data.vehicle ? this.data.vehicle. : null, // 自重
        panel: 'panel', // 容器
        load: parseFloat(this.data.weightSum / 1000).toFixed(2), // 载重
        policy: this.policy // 路线规则1-11(1：避免拥堵；2：不走高速；3：避免收费；4：避免拥堵&不走高速；5：避免收费&不走高速；6：避免拥堵&避免收费；7：避免拥堵&避免收费&不走高速；8：高速优先；9：避免拥堵&高速优先；10：时间最短；11：避免拥堵&速度优先&避免收费)
      })
      let truckDrivingPath = []
      truckDrivingPath.push({ lnglat: [start.longitude, start.latitude] }) // 起点
      this.path.forEach(item => {
        truckDrivingPath.push({ lnglat: [item.longitude, item.latitude] }) // 路径
      })
      this.truckDriving.search(truckDrivingPath, function(status, result) {
        if (status === 'complete') {
          self.pathPlanResult.data = result
          self.pathPlanResult.isPathPlanSuccess = true
          // 跳转高德app导航
          // window.location.href = `http://uri.amap.com/marker?position=${104.009893},${30.637803}&name=${'武侯'}&coordinate=gaode&callnative=1`
        } else {
          console.log('获取配送路线数据失败：' + result)
        }
      })
    },
    // 最短路径排序算法
    computeDis(start = {}, arr = [], result = [], i = 1) {
      let minDistance = 0
      let spotIndex = 0
      let startSpot = new AMap.LngLat(start.longitude, start.latitude)
      arr.forEach((el, index) => {
        let waySpot = new AMap.LngLat(el.longitude, el.latitude)
        let distance = Math.round(AMap.GeometryUtil.distanceOfLine([startSpot, waySpot]))
        minDistance = index == 0 ? distance : minDistance
        if (distance < minDistance) {
          minDistance = distance
          spotIndex = index
        }
      })
      result.push(arr[spotIndex])
      let arrTemp = arr.filter((item, index) => spotIndex != index)
      if (arrTemp.length > 1) {
        this.computeDis(arr[spotIndex], arrTemp, result, ++i)
      } else if (arrTemp.length == 1) {
        result.push(arrTemp[0])
        return true
      } else {
        return result
      }
      return result
      // return arr[spotIndex]
    },
    // 确认执行路径规划
    async submitPathPlan() {
      if (!this.pathPlanResult.isPathPlanSuccess) {
        this.$message.warning('路径规划未成功')
        return
      }
      let query = '?departId=' + this.data.id + '&actualDistance=' + this.pathPlanResult.data.routes[0].distance
      let param = []
      this.path.forEach((item, index) => {
        param.push({
          longitude: item.longitude,
          latitude: item.latitude,
          id: item.id,
          sequence: this.path.length - index
        })
      })
      let res = await this.$API.departureManage.reqPathPlanning(query, param)
      if (res) {
        this.$router.push({ path: '/departureManage/departurePlanDetail', query: { id: this.data.id, status: this.data.status }})
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.map{
  width: calc(100% - 1px);
  height: calc(100%);
}
.container {
  width: 100%;
  height: 100%;
  position: relative;
  left: 50%;
  top: 50%;
  transform: translate3d(-50%, -50%, 0);
  border: 1px solid #999;
  .submit-path-plan{
    position: absolute;
    z-index: 2;
    top: 10px;
    right: 250px;
  }
  .setting{
    position: absolute;
    z-index: 2;
    top: 10px;
    right: 210px;
    font-size: 20px;
  }
}
#panel{
  position: fixed;
  z-index: 3;
  top: 0;
  right: 0;
  width: 200px;
  height: 400px;
  overflow-y: auto;
}
</style>
